//microcommand define qface
const { readFile, stat } = require("fs/promises")
const { resolve } = require("path")
const { pathToFileURL } = require("url")
signature("<face:fragment>", { strictOptions: true })
option("static", "-s")
option("raw", "-r")
inject({ optional: ["ffmpeg"] })
before(({ session, options, args }) => {
  if (options.help) return
  if (!args.length) return session.execute({ name: "help", args: [name] })
})
const dir = resolve(process.env.HOME, ".config/QQ/nt_qq/global/nt_data/Emoji/emoji-resource")
async function getFace(input) {
  const [faceEl] = h.select(input, "face")
  if (faceEl) return { type: "sysface", id: faceEl.attrs.id }
  const text = h("", input).toString(true).trim()
  const data = JSON.parse(await readFile(resolve(dir, "face_config.json"), "utf8"))
  for (const type of ["sysface", "emoji"])
    for (const o of data[type])
      if (o.QSid == text || String(o.QDes).replace("/", "") === text)
        return { type, id: String(o.AQLid) }
}
function isFile(path) {
  return stat(path).then(s => s.isFile()).catch(() => false)
}
action(async ({ session, options }, input) => {
  const image = path => h[options.raw ? "file" : "image"](pathToFileURL(path).href)
  const face = await getFace(input)
  if (!face) return session.i18n(".not-found")
  if (face.type === "emoji") return image(resolve(dir, `emoji_res/emoji_${face.id.padStart(3, "0")}.png`))
  apng: if (!options.static) {
    const apngPath = resolve(dir, `sysface_res/apng/s${face.id}.png`)
    if (!await isFile(apngPath)) break apng
    if (!options.raw && ctx.ffmpeg) {
      const apng = await readFile(apngPath)
      const gif = await ctx.ffmpeg.builder().input(apng).outputOption("-lavfi", "split[v],palettegen,[v]paletteuse", "-f", "gif").run("buffer")
      return h.image(gif, "image/gif")
    }
    return image(apngPath)
  }
  return image(resolve(dir, `sysface_res/static/s${face.id}.png`))
})
locale("zh-CN", {
  description: "获取高清 QQ 表情",
  options: { static: "不获取动图", raw: "输出原始文件" },
  messages: { "not-found": "未找到指定的 QQ 表情…" },
})